package com.zhixin.fans.ks.api;


import com.alibaba.fastjson.JSON;
import com.androidnetworking.common.Priority;
import com.rx2androidnetworking.Rx2ANRequest;
import com.rx2androidnetworking.Rx2AndroidNetworking;
import com.tencent.mmkv.MMKV;
import com.trello.rxlifecycle3.android.ActivityEvent;
import com.zhixin.fans.ks.KeyConstant;
import com.zhixin.fans.ks.api.res.ChargeHistory;
import com.zhixin.fans.ks.api.res.CoinHistory;
import com.zhixin.fans.ks.api.res.CoinHistoryRes;
import com.zhixin.fans.ks.api.res.CoinOption;
import com.zhixin.fans.ks.api.res.CoinOptionRes;
import com.zhixin.fans.ks.api.res.FirstChangeInfo;
import com.zhixin.fans.ks.api.res.FirstChargeRes;
import com.zhixin.fans.ks.api.res.GoodOption;
import com.zhixin.fans.ks.api.res.GoodOptionRes;
import com.zhixin.fans.ks.api.res.IndexModule;
import com.zhixin.fans.ks.api.res.LoginEntity;
import com.zhixin.fans.ks.api.res.ModuleListRes;
import com.zhixin.fans.ks.api.res.MutualContent;
import com.zhixin.fans.ks.api.res.MutualDetail;
import com.zhixin.fans.ks.api.res.MutualTalk;
import com.zhixin.fans.ks.api.res.OrderHistory;
import com.zhixin.fans.ks.api.res.OrderHistoryRes;
import com.zhixin.fans.ks.api.res.OrderInfo;
import com.zhixin.fans.ks.api.res.ServiceContactRes;
import com.zhixin.fans.ks.api.res.SubModule;
import com.zhixin.fans.ks.api.res.UserInfoRes;
import com.zhixin.fans.ks.api.res.UserToken;
import com.zhixin.fans.ks.api.res.VipOption;
import com.zhixin.fans.ks.api.res.VipOptionRes;
import com.zhixin.fans.ks.api.res.WxPayInfo;

import org.eenie.common.api.ApiEnv;
import org.eenie.common.api.ThreadTransformer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.BehaviorSubject;

public class CommonApi {

    private int PAGE_SIZE = 20;
    private String API_URL = "http://ms2client.ksfsvip.com" + "/" + ApiEnv.BASE_PATH;

    BehaviorSubject<ActivityEvent> mSubject;


    /**
     * QQ登录
     *
     * @param openid
     * @param headPicture
     * @param nickName
     * @return
     */
    public Observable<UserToken> loginByQQ(String openid, String headPicture, String nickName) {
        Map<String, Object> params = new HashMap<>();
        params.put("loginType", "QQ");
        params.put("headPicture", headPicture);
        params.put("nickName", nickName);
        params.put("threeId", openid);
        return post("user.login", params)
                .getObjectObservable(UserToken.class)
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 微信登录
     *
     * @param openid
     * @param headPicture
     * @param nickName
     * @return
     */
    public Observable<UserToken> loginByWx(String openid, String headPicture, String nickName, String unid) {
        Map<String, Object> params = new HashMap<>();
        params.put("loginType", "WX");
        params.put("headPicture", headPicture);
        params.put("nickName", nickName);
        params.put("threeId", openid);
        params.put("unid", unid);
        return post("user.login", params)
                .getObjectObservable(UserToken.class)
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public Observable<UserInfoRes> fetchUserInfo(String token) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        return post("user.getUserInfo", params)
                .getObjectObservable(UserInfoRes.class)
                .compose(new ThreadTransformer<>(mSubject));
    }


    /**
     * 获取充值历史
     *
     * @return
     */
    public Observable<List<ChargeHistory>> fetchChangeHistory() {
        return get("active-list")
                .getObjectListObservable(ChargeHistory.class)
                .compose(new ThreadTransformer<>(mSubject));
    }


    /**
     * 获取首页模块
     *
     * @return
     */
    public Observable<List<IndexModule>> fetchModule() {
        return post("good.listGoodClass", new HashMap<>())
                .getObjectObservable(ModuleListRes.class)
                .map(new Function<ModuleListRes, List<IndexModule>>() {
                    @Override
                    public List<IndexModule> apply(ModuleListRes moduleListRes) throws Exception {
                        return moduleListRes.getGoodClassList();
                    }
                })
                .compose(new ThreadTransformer<>(mSubject));
    }


    /**
     * 获取互动列表
     *
     * @param uid
     * @param offset
     * @return
     */
    public Observable<List<MutualContent>> fetchMutual(int uid, int offset) {
        Map<String, Object> params = new HashMap<>();
        params.put("uid", uid);
        params.put("offset", offset);
        params.put("limit", PAGE_SIZE);
        return post("hd-list", params)
                .getObjectListObservable(MutualContent.class)
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 获取首充信息
     *
     * @return
     */
    public Observable<FirstChangeInfo> fetchFirstChange() {
        return get("sc")
                .getObjectObservable(FirstChangeInfo.class)
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 获取客服联系方式
     *
     * @return
     */
    public Observable<ServiceContactRes> fetchContact() {
        Map<String, Object> params = new HashMap<>();
        return post("config.customerInfo", params)
                .getObjectObservable(ServiceContactRes.class)
                .compose(new ThreadTransformer<>(mSubject));
    }


    /**
     * 获取首充预支付信息
     *
     * @return
     */
    public Observable<FirstChargeRes> fetchFirstChangePay() {
        Map<String, Object> params = new HashMap<>();
        return post("point.firstPointGood", params)
                .getObjectObservable(FirstChargeRes.class)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }


    /**
     * 获取互动详情
     *
     * @return
     */
    public Observable<MutualDetail> fetchMutualDetail(int uid, int id) {
        Map<String, Object> params = new HashMap<>();
        params.put("uid", uid);
        params.put("id", id);
        return post("hd-detail", params)
                .getObjectObservable(MutualDetail.class)
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 发表互动评论
     *
     * @return
     */
    public Observable<List<MutualTalk>> sendMutualTalk(int uid, int id, String content) {
        Map<String, Object> params = new HashMap<>();
        params.put("uid", uid);
        params.put("id", id);
        params.put("content", content);
        return post("hd-dis", params)
                .getObjectListObservable(MutualTalk.class)
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 获取粉币列表
     *
     * @return
     */
    public Observable<List<CoinOption>> fetchCoinList() {
        return post("point.listPointGood", new HashMap<>())
                .getObjectObservable(CoinOptionRes.class)
                .map(new Function<CoinOptionRes, List<CoinOption>>() {
                    @Override
                    public List<CoinOption> apply(CoinOptionRes coinOptionRes) throws Exception {
                        return coinOptionRes.getPointGoodList();
                    }
                })
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 获取粉币列表
     *
     * @return
     */
    public Observable<List<VipOption>> fetchVipList() {
        return post("vip.listVipGood", new HashMap<>())
                .getObjectObservable(VipOptionRes.class)
                .map(new Function<VipOptionRes, List<VipOption>>() {
                    @Override
                    public List<VipOption> apply(VipOptionRes vipOptionRes) throws Exception {
                        return vipOptionRes.getVipGoodList();
                    }
                })
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 获取预支付信息
     *
     * @return
     */
    public Observable<WxPayInfo> fetchPayInfo(int orderId) {
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", orderId);
        return post("goodOrder.setPrepayInfo", params)
                .getObjectObservable(WxPayInfo.class)
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 获取模块内容
     *
     * @param type
     * @return
     */
    public Observable<List<SubModule>> fetchModuleInfo(int type) {
        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        return post("goods-type", params)
                .getObjectListObservable(SubModule.class)
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 获取模块商品列表
     *
     * @return
     */
    public Observable<List<GoodOption>> fetchModuleGoods(int classId) {
        Map<String, Object> params = new HashMap<>();
        params.put("categoryId", classId);
        return post("good.listGoodInfo", params)
                .getObjectObservable(GoodOptionRes.class)
                .map(new Function<GoodOptionRes, List<GoodOption>>() {
                    @Override
                    public List<GoodOption> apply(GoodOptionRes goodOptionRes) throws Exception {
                        return goodOptionRes.getGoodInfos();
                    }
                })
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 生成订单
     *
     * @return
     */
    public Observable<String> submitOrder(String desc, int goodId) {
        Map<String, Object> params = new HashMap<>();
        params.put("desc", desc);
        params.put("goodId", goodId);
        return post("userPointOrder.addUserPointOrder", params)
                .getObjectObservable(String.class)
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 生成订单
     *
     * @return
     */
    public Observable<OrderInfo> submitPayOrder(String goodType, int goodId) {
        Map<String, Object> params = new HashMap<>();
        params.put("goodType", goodType);
        params.put("goodId", goodId);
        return post("goodOrder.addOrder", params)
                .getObjectObservable(OrderInfo.class)
                .compose(new ThreadTransformer<>(mSubject));
    }


    /**
     * 获取订单列表
     *
     * @return
     */
    public Observable<List<OrderHistory>> fetchOrders(int page) {
        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("pageSize", PAGE_SIZE);
        return post("goodOrder.listPayOrder", params)
                .getObjectObservable(OrderHistoryRes.class)
                .map(new Function<OrderHistoryRes, List<OrderHistory>>() {
                    @Override
                    public List<OrderHistory> apply(OrderHistoryRes orderHistoryRes) throws Exception {
                        return orderHistoryRes.getOrderInfos();
                    }
                })
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 获取充值列表
     *
     * @return
     */
    public Observable<List<CoinHistory>> fetchChargeList(int page) {
        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("pageSize", PAGE_SIZE);
        return post("userPointOrder.listUserPointOrder", params)
                .getObjectObservable(CoinHistoryRes.class)
                .map(new Function<CoinHistoryRes, List<CoinHistory>>() {
                    @Override
                    public List<CoinHistory> apply(CoinHistoryRes coinHistoryRes) throws Exception {
                        return coinHistoryRes.getUserPointorderList();
                    }
                })
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 获取用户发布的互动列表
     *
     * @param uid
     * @param offset
     * @return
     */
    public Observable<LoginEntity> fetchUserMutuals(String uid, int offset) {
        Map<String, Object> params = new HashMap<>();
        params.put("uid", uid);
        params.put("offset", offset);
        params.put("limit", PAGE_SIZE);
        return post("my-hd", params)
                .getObjectObservable(LoginEntity.class)
                .compose(new ThreadTransformer<>(mSubject));
    }

    /**
     * 获取用户发布的互动列表
     *
     * @param uid
     * @return
     */
    public Observable<String> sendMutuals(int uid, String imgUrl, String desc) {
        Map<String, Object> params = new HashMap<>();
        params.put("uid", uid);
        params.put("img_url", imgUrl);
        params.put("desc", desc);
        return post("add-hd", params)
                .getObjectObservable(String.class)
                .compose(new ThreadTransformer<>(mSubject));
    }


    private Rx2ANRequest post(String method, Map<String, Object> params) {
        return Rx2AndroidNetworking.post("http://api.dyvip178.com/newksApi/kuaiditu/api")
                .addBodyParameter("param", JSON.toJSONString(generateParams(method, params)))
                .setPriority(Priority.HIGH)
                .build();
    }


    private Rx2ANRequest get(String method) {
        return Rx2AndroidNetworking.get(API_URL + "/{path}")
                .addPathParameter("path", method)
                .setPriority(Priority.HIGH)
                .build();
    }


    private Rx2ANRequest get(String method, Map<String, Object> params) {
        return Rx2AndroidNetworking.get(API_URL + "/{path}")
                .addQueryParameter(params)
                .setPriority(Priority.HIGH)
                .addPathParameter("path", method)
                .build();
    }

    public void bindLife(BehaviorSubject<ActivityEvent> subject) {
        mSubject = subject;
    }


    private Map<String, Object> generateParams(String method, Map<String, Object> data) {
        Map<String, Object> params = new HashMap<>();
        data.put("token", MMKV.defaultMMKV().getString(KeyConstant.KEY_TOKEN, ""));
        params.put("timestamp", System.currentTimeMillis());
        params.put("source", "AND");
        params.put("market", "COMMON");
        params.put("method", method);
        params.put("data", data);
        params.put("sign", "C431253AFEF913782198ABECC640C280");
        params.put("appId", "123456");
        return params;
    }


    //    private RequestBody generateFormBody(Map<String, Object> params) {
//        FormBody.Builder builder = new FormBody.Builder();
//        for (String key : params.keySet()) {
//            builder.add(key, String.valueOf(params.get(key)));
//        }
//        return builder.build();
//    }

}
